const Path = require('path');
const Fs = require('fs');

exports.template = Fs.readFileSync(Path.join(__dirname, 'index.html'), 'utf-8');
exports.style = Fs.readFileSync(Path.join(__dirname, 'index.css'), 'utf-8');
exports.$ = {
    readProject: '#readProject',
    saveProject: '#saveProject',
    openProject: '#openProject',
    projectFile: '#projectFile',


    readEditor: '#readEditor',
    saveEditor: '#saveEditor',
    openEditor: '#openEditor',
    editorFile: '#editorFile',

    input: '#input',
    value: '#value',
}

let plugin = 'hello-profile';

let projectProfile = Path.join(Editor.Project.path, 'settings', Editor.App.version, 'packages', `${plugin}.json`);
let editorProfile = Path.join(Editor.Project.path, 'profiles', Editor.App.version, 'packages', `${plugin}.json`);

function bindClick (el, cb) {
    el.addEventListener('click', () => {
        cb && cb();
    })
}

function updateProfile (els) {
    els.editorFile.innerText = editorProfile;
    els.projectFile.innerText = projectProfile;
}

exports.ready = async function () {
    this.$.input.value = 'profile-test';
    this.$.value.value = '1';
    updateProfile(this.$);

    bindClick(this.$.readProject, async () => {
        let input = this.$.input.value;
        let value = await Editor.Profile.getProject(plugin, input);
        console.log(value)
        this.$.value.value = value;
    })
    bindClick(this.$.saveProject, () => {
        let input = this.$.input.value;
        let value = this.$.value.value;
        if (input && value) {
            Editor.Profile.setProject(plugin, input, value);
            console.log('save', value)
        } else {
            console.log('key/value 无效')
        }
    })
    bindClick(this.$.openProject, () => {
        if (Fs.existsSync(projectProfile)) {
            let data = JSON.parse(Fs.readFileSync(projectProfile, 'utf-8'));
            console.log(data)
        }
    })

    bindClick(this.$.readEditor, async () => {
        let input = this.$.input.value;
        let value = await Editor.Profile.getConfig(plugin, input);
        console.log(value)
        this.$.value.value = value;
    })
    bindClick(this.$.saveEditor, () => {
        let input = this.$.input.value;
        let value = this.$.value.value;
        if (input && value) {
            Editor.Profile.setConfig(plugin, input, value);
            console.log('save', value)
        } else {
            console.log('key/value 无效')
        }
    })
    bindClick(this.$.openEditor, () => {
        if (Fs.existsSync(editorProfile)) {
            let data = JSON.parse(Fs.readFileSync(editorProfile, 'utf-8'));
            console.log(data)
        }
    })
}


